package com.yt.loadbalance.impl;

import com.yt.loadbalance.MyLoadBalance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Classname MyLoadBalanceImpl
 * @Description  自定义的轮询规则
 * @Date 2021/10/20 11:01
 * @Create by 杨涛
 */
@Component
@Slf4j
public class MyLoadBalanceImpl implements MyLoadBalance {

    AtomicInteger atomicInteger=new AtomicInteger(0);
    public int getAndIncrement(){
        int current=0;
        int next;
        int max=Integer.MAX_VALUE;
        do{
            current=atomicInteger.get();
            next = current < max ? current+1:0;
        }while (!atomicInteger.compareAndSet(current,next));
        log.debug(max+"current:"+current +"    ---  "+"next:"+next);
        return next;
    }

    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstanceList) {
        int index = getAndIncrement() % serviceInstanceList.size();
        return serviceInstanceList.get(index);
    }

    public static void main(String[] args) {
        MyLoadBalanceImpl mlbi=new MyLoadBalanceImpl();
        for (;;){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(mlbi.getAndIncrement());

        }
    }
}
